package com.example.demo.utils;

import java.util.Random;

/**
 * @author Lucy
 * @create 2024-01-05 16:20
 */
public class CodeUtil {

    private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    public static String generateMixCode(int length) {
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = (int) (Math.random() * ALPHABET.length());
            char character = ALPHABET.charAt(index);
            code.append(character);
        }
        return code.toString();
    }

    /**
     * 生成指定长度的随机数字验证码
     *
     * @param length 验证码的长度
     * @return 随机生成的验证码
     */
    public static String generateCode(int length) {
        // 创建一个StringBuilder来构建验证码
        StringBuilder verificationCode = new StringBuilder(length);
        // 创建一个Random对象来生成随机数
        Random random = new Random();
        // 循环指定的长度，生成随机数字并添加到StringBuilder中
        for (int i = 0; i < length; i++) {
            // 生成一个0（包括）到9（不包括）之间的随机数字
            int digit = random.nextInt(10);
            verificationCode.append(digit);
        }
        // 将StringBuilder转换为String并返回
        return verificationCode.toString();
    }

}
